package Collection;

import java.util.HashSet;
import java.util.Objects;

/*
    自定义数据类型使用Set接口的实现类必须先重写hashCode与equals方法
    Set接口的实现类中判断元素相等的使用的是hash值，List接口的实现类中使用的是equals判断
 */
public class HashSetDemo {
    public static void main(String[] args) {
        HashSet hashSet=new HashSet();
        hashSet.add("a");
        hashSet.add(true);
        hashSet.add("c");
        hashSet.add("a");
        System.out.println(hashSet);
        HashSet<Student> hashSet1=new HashSet();
        Student stu1=new Student("yao",1);
        Student stu2=new Student("yao",1);
        hashSet1.add(stu1);
        hashSet1.add(stu2);
        System.out.println(hashSet1);
    }
}
class Student implements Comparable{
    String name;
    int no;

    public Student(String name, int no) {
        this.name = name;
        this.no = no;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", no=" + no +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return no == student.no &&
                Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, no);
    }

    //compareTo是将这个对象与前一个对象相比
    @Override
    public int compareTo(Object o) {
        Student student=(Student)o;
        return this.name.length()-student.name.length();
    }
}
